/*
 * @Company: zmn
 * @Author: tangmaoqin@zmn.cn
 * @Description: 根据通用权限id查找对应平台的权限名
 * @Date: 2024-08-11 11:48:37
 */
import { permissionMap } from '../constants';
import { PERMISSION_ID_ENUM } from '../enums';

import type { PermissionResult } from '../types';

/**
 * 根据通用权限id查找对应平台的权限名
 * @param options
 * @returns
 */
export const queryPermissionNamesByPermissionId = (options: {
  /** 权限ID */
  permission: string[] | string;
  /** 对应平台 默认Android */
  platform?: 'android' | 'ios';
  /** 权限类型 1: read, 2: write */
  type?: number;
}): string | string[] => {
  const { permission, platform = 'android', type = 1 } = options || {};
  const isArr = Array.isArray(permission);
  const permissionIds = isArr ? permission : [permission];

  const permissionNames = permissionIds
    .map((id) => {
      let permissionName = '';
      switch (type) {
        case 2: {
          permissionName = permissionMap[id][platform]?.write || permissionMap[id][platform] || '';
          break;
        }
        case 1:
        default: {
          permissionName = permissionMap[id][platform]?.read || permissionMap[id][platform] || '';
        }
      }
      return permissionName;
    })
    .filter((permissionName) => permissionName);

  if (isArr) {
    return permissionNames;
  }
  return permissionNames[0];
};

/**
 * 根据权限id查询权限校验的结果
 * @param permissionResultList 权限校验结果列表
 * @param permissionId 权限id
 * @returns { PermissionResult }
 */
export const queryPermissionCheckedResultByPermissionId = (
  permissionResultList: PermissionResult[],
  permissionId: PERMISSION_ID_ENUM
): PermissionResult => {
  return permissionResultList?.find((permissionResItem) => permissionResItem?.permissionId === permissionId) as PermissionResult;
};
